package features.advance.mybatis.sqlbuilder;

import org.apache.ibatis.jdbc.SQL;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author LIN
 * @date 2022-01-11 14:54
 *  Mybatis SQL语句构构建器
 */
public class Demo {
    /**
     * 预编译demo
     */
    public void test01(){
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8","root","root")){
            Class.forName("com.mysql.cj.jdbc.Driver");

            String sqlString = "select * from test01 where id = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sqlString);
            preparedStatement.setString(1,"1");

            ResultSet execute = preparedStatement.executeQuery();
            int count = execute.getMetaData().getColumnCount();
            while (execute.next()) {
                for (int i = 1; i <= count; i++) {
                    String columnName = execute.getMetaData().getColumnName(i);
                    System.out.print(columnName+":"+execute.getString(i)+"\t");
                }
                System.out.println();
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            // 关闭数据库连接
        }
    }
    public static void main(String[] args) {
        Demo demo = new Demo();
//        SQL sql = demo.getDefineSql();
//        System.out.println(sql);
        demo.test01();

    }

    private  SQL getDefineSql() {
        SQL sql = new SQL() {{
            SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME");
            SELECT("P.LAST_NAME, P.CREATED_ON, P.UPDATED_ON");
            FROM("PERSON P","ACCOUNT A");
            INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID","COMPANY C on D.COMPANY_ID = C.ID");
            WHERE("P.ID = A.ID");
            WHERE("P.FIRST_NAME like ?");
            OR();
            WHERE("P.LAST_NAME like ?");
            GROUP_BY("P.ID");
            HAVING("P.LAST_NAME like ?");
            OR();
            HAVING("P.FIRST_NAME like ?");
            ORDER_BY("P.ID");
            ORDER_BY("P.FULL_NAME");
        }};
        return sql;
    }


}
